package array.binarysearch;

/**
 * @ClassName MySqrt
 * @Description TODO
 * @Author lenovo
 * @Date 2023-02-10 11:04
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class MySqrt {

    /**
     * 给你一个非负整数 x ，计算并返回 x 的 算术平方根 。
     * <p>
     * 由于返回类型是整数，结果只保留 整数部分 ，小数部分将被 舍去 。
     * <p>
     * 注意：不允许使用任何内置指数函数和算符，例如 pow(x, 0.5) 或者 x ** 0.5 。
     * 5
     * left = 0 ,right = 5 mid = 2 4<=5 index = 2
     * left = 3,right = 5 mid = 4 16>5
     * left = 3,right = 3 mid = 3 9>5
     * left = 3,right =2 return index = 2;
     *
     * @param x
     * @return
     */
    public int mySqrt(int x) {
        int index = -1;
        int left = 0;
        int right = x;
        while (left <= right) {
            int mid = (left + right) / 2;
            if ((long)mid * mid <= x) {
                index = mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return index;
    }

    public static void main(String[] args) {
        MySqrt mySqrt = new MySqrt();
        System.out.println(mySqrt.mySqrt(16));
    }
}